package com.itheima.controller.store.course;

import com.github.pagehelper.PageInfo;
import com.itheima.controller.BaseServlet;
import com.itheima.domain.Catalog;
import com.itheima.domain.Course;
import com.itheima.utils.BeanUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/store/course/*")
public class CourseServlet extends BaseServlet {
    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String page = req.getParameter("page");
        String pageSize = req.getParameter("pageSize");

        List<Course> list=courseService.findAll(page,pageSize);
        PageInfo<Course> pageInfo = new PageInfo<Course>(list);
        req.setAttribute("page",pageInfo);
        req.getRequestDispatcher("/pages/store/course/list.jsp").forward(req,resp);
    }

        private void save(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html;charset=UTF-8");

            Course course = BeanUtil.fillBean(req, Course.class);
            courseService.save(course);

            findAll(req,resp);
    }
    private void findById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        String id = req.getParameter("id");
        Course id1 = courseService.findById(id);
        req.setAttribute("course",id1);
        req.getRequestDispatcher("/pages/store/course/update.jsp").forward(req,resp);
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        Course course = BeanUtil.fillBean(req, Course.class);
        courseService.update(course);


        findAll(req,resp);
    }
    private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        String id = req.getParameter("id");
        courseService.delete(id);


        findAll(req,resp);
    }



}
